<template>
  <div class="box">
    <div class="boxTop">
      <div class="boxTopTop" v-if="search">
        <span>状态：</span>
        <el-select v-model="value" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-button type="primary" class="el-icon-search" @click="handleAll"
          >搜索</el-button
        >
        <el-button class="el-icon-delete" @click="handleClear">清空</el-button>
      </div>
      <div class="boxTopBottom">
        <div class="boxTopBottomLeft">
          <el-button type="primary" class="el-icon-plus" @click="handleAddOpen"
            >新增</el-button
          >
          <el-button
            type="danger"
            :disabled="multipleSelection.length === 0"
            @click="handleBatchDel"
            >批量删除</el-button
          >
        </div>
        <div>
          <el-button icon="el-icon-refresh" circle></el-button>
          <el-button icon="el-icon-search" circle @click="handleSearch"></el-button>
        </div>
      </div>
    </div>
    <div class="boxMiddle">
      <div class="boxMiddleTop">
        <div>
          <span class="xuan"
            >当前表格已选择<i>{{ this.xuanTiao }}</i
            >项<span @click="handleQing">清空</span></span
          >
        </div>
      </div>
      <div class="boxMiddleBottom">
        <el-table
          ref="multipleTable"
          border
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center"> </el-table-column>
          <el-table-column prop="imgUrl" label="轮播图片" align="center">
            <template slot-scope="scope">
              <img :src="scope.row.imgUrl" style="width: 100px; height: 100px" />
            </template>
          </el-table-column>
          <el-table-column prop="seq" label="顺序" align="center"> </el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            width="120"
            show-overflow-tooltip
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.status === 1 ? "正常" : "禁用" }}
            </template>
          </el-table-column>
          <el-table-column label="操作" show-overflow-tooltip align="center">
            <template slot-scope="scope">
              <el-button
                type="primary"
                class="el-icon-edit"
                @click="handleModify(scope.row)"
                >修改</el-button
              >
              <el-button
                type="danger"
                class="el-icon-delete"
                @click="handleDel(scope.row.imgId)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="boxBottom">
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="obj.currentPage"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="this.obj.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="obj.total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="moTopic"
      :visible.sync="dialogVisibleA"
      width="30%"
      :before-close="handleClosemoa"
    >
      <div class="boxMoa">
        <div class="boxMoaTop">
          <span>轮播图片</span>
          <el-upload
            class="avatar-uploader"
            action="http://47.104.167.34:9305/apis/admin/file/upload/element"
            :headers="authorization"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
        <div class="boxMoaMiddle">
          <span>顺序</span>
          <el-input
            v-model="moA.seq"
            placeholder="请输入内容"
            class="moAinput"
          ></el-input>
        </div>
        <div class="boxMoaLeg">
          <span class="boxMoaLegLeft">状态</span>
          <div class="boxMoaLegRight">
            <el-radio v-model="moA.radioA" :label="0">禁用</el-radio>
            <el-radio v-model="moA.radioA" :label="1">正常</el-radio>
          </div>
        </div>
        <div class="boxMoaLeg">
          <span class="boxMoaLegLeft">状态</span>
          <div class="boxMoaLegRight">
            <el-radio v-model="moA.radioB" :label="-1">无</el-radio>
            <el-radio v-model="moA.radioB" :label="0">商品</el-radio>
          </div>
        </div>
        <div class="boxMoaBottom" v-if="moA.radioB === 0">
          <el-button @click="dialogVisibleB = true">选择商品</el-button>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleAdd">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="选择商品" :visible.sync="dialogVisibleB" width="30%">
      <span>选择商品</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleB = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleB = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 控制搜索栏开关
      search: true,
      // 选项
      options: [
        {
          value: "0",
          label: "禁用",
        },
        {
          value: "1",
          label: "正常",
        },
      ],
      value: "",
      // 模态框题目
      moTopic: "",
      // 模态框图片
      imageUrl: "",
      // 模态框上传图片请求头
      authorization: {
        Authorization: localStorage.getItem("token"),
      },
      // 表格数据
      tableData: [],
      multipleSelection: [],
      // 选中了几条
      xuanTiao: 0,
      // 选中的id
      idxs: [],
      // 分页
      obj: {
        current: 1,
        size: 10,
        total: 0,
        currentPage: 1,
      },
      // 第一个模态框开关
      dialogVisibleA: false,
      // 第二个模态框开关
      dialogVisibleB: false,
      // 第一个模态框数据
      moA: {
        idx: "",
        seq: "0",
        radioA: 0,
        radioB: -1,
      },
    };
  },
  methods: {
    // 清空搜索
    handleClear() {
      this.value = "";
    },
    // 控制显示隐藏搜索框
    handleSearch() {
      this.search = !this.search;
    },
    // 表格选择批量删除
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.xuanTiao = this.multipleSelection.length;
      console.log(this.multipleSelection, "111111111");
      for (let i = 0; i < this.multipleSelection.length; i++) {
        console.log(this.multipleSelection[i].imgId);
        this.idxs.push(this.multipleSelection[i].imgId);
      }
      console.log(this.idxs, "批量删除id");
    },
    // 新增模态框打开
    handleAddOpen() {
      this.moTopic = "新增";
      this.dialogVisibleA = true;
    },
    // 新增数据
    handleAdd() {
      const uploadTime = new Date().toISOString().replace("T", " ").replace("Z", "");
      if (this.moA.idx === "") {
        this.$axios
          .post(
            "/api/admin/indexImg", // URL
            {
              // 请求体 (data)
              des: "",
              imgId: 0,
              imgUrl: this.imageUrl,
              link: null,
              pic: null,
              prodName: null,
              relation: null,
              seq: this.moA.seq,
              shopId: 1,
              status: this.moA.radioA,
              t: new Date().getTime(),
              title: null,
              type: this.moA.radioB,
              uploadTime: uploadTime,
            },
            {
              // 配置对象 (config)
              headers: {
                authorization: localStorage.getItem("token"),
              },
            }
          )
          .then((res) => {
            console.log(res, "新增数据");
            if (res.data.code === "00000") {
              this.$message({
                message: "操作成功",
                type: "success",
              });
              this.dialogVisibleA = false;
              this.handleAll();
              this.imageUrl = "";
              this.moA.seq = "0";
            } else {
              this.$message({
                message: "操作失败",
                type: "error",
              });
            }
          })
          .catch((error) => {
            console.error(error);
          });
      } else {
        this.$axios
          .put(
            "/api/admin/indexImg", // URL
            {
              // 请求体 (data)
              des: "",
              imgId: this.moA.idx,
              imgUrl: this.imageUrl,
              link: null,
              pic: null,
              prodName: null,
              relation: null,
              seq: this.moA.seq,
              shopId: 1,
              status: this.moA.radioA,
              t: new Date().getTime(),
              title: null,
              type: this.moA.radioB,
              uploadTime: uploadTime,
            },
            {
              // 配置对象 (config)
              headers: {
                authorization: localStorage.getItem("token"),
              },
            }
          )
          .then((res) => {
            console.log(res, "编辑数据");
            if (res.data.code === "00000") {
              this.$message({
                message: "操作成功",
                type: "success",
              });
              this.dialogVisibleA = false;
              this.handleAll();
              this.imageUrl = "";
              this.moA.seq = "0";
            } else {
              this.$message({
                message: "操作失败",
                type: "error",
              });
            }
          })
          .catch((error) => {
            console.error(error);
          });
      }
    },
    // 模态框图片上传
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 叉号关闭第一个模态框清除数据
    handleClosemoa() {
      this.imageUrl = "";
      this.dialogVisibleA = false;
    },
    // 清空批量删除
    handleQing() {
      this.$refs.multipleTable.clearSelection();
    },
    // 表格数据
    handleAll() {
      this.$axios
        .get("/api/admin/indexImg/page", {
          params: {
            // t: new Date().getTime(),
            current: this.obj.current,
            size: this.obj.size,
            status: this.value,
          },
          headers: {
            authorization: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          this.obj.total = res.data.data.total;
          this.tableData = res.data.data.records;
          console.log(res.data.data.records, "表格数据");
        });
    },
    // 删除表格数据
    handleDel(idx) {
      console.log(idx, "删除");
      this.$confirm("此操作将执行[删除]操作, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .delete("/api/admin/indexImg", {
              data: [idx],
              headers: {
                authorization: localStorage.getItem("token"),
              },
            })
            .then((res) => {
              console.log(res, "删除数据");
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.handleAll();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //批量删除
    handleBatchDel() {
      let arr = [];
      arr = Array.from(new Set(this.idxs));
      console.log(arr, "去重id");
      this.$confirm("此操作将执行[批量删除]操作, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .delete("/api/admin/indexImg", {
              data: arr,
              headers: {
                authorization: localStorage.getItem("token"),
              },
            })
            .then((res) => {
              console.log(res, "删除数据");
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.handleAll();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.obj.size = val;
      this.handleAll();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.obj.current = val;
      this.handleAll();
    },
    // 详情打开第一个模态框
    handleModify(row) {
      console.log(row, "详情");
      this.moTopic = "修改";
      this.moA.idx = row.imgId;
      this.moA.seq = row.seq;
      this.moA.radioA = row.status;
      this.moA.radioB = row.type;
      this.imageUrl = row.imgUrl;
      this.dialogVisibleA = true;
    },
  },
  mounted() {
    this.handleAll();
  },
};
</script>

<style scoped lang="scss">
.box::v-deep {
  width: 98%;
  height: 98%;
  padding: 1%;
  .boxTop {
    width: 100%;
    .el-select {
      margin-right: 10px;
    }
  }
  .boxTopBottom {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
  }
  .boxMiddleTop {
    div {
      margin: 10px 0;
      .xuan {
        padding: 7px 12px;
        color: #02a1e9;
        border: 1px solid rgba(2, 161, 233, 0.2);
        border-radius: 4px;
        background-color: rgba(2, 161, 233, 0.1);
        i {
          font-size: 20px;
        }
      }
    }
  }
  .boxMiddleBottom {
    margin-top: 10px;
  }
  // 上传样式
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .boxMoaTop {
    display: flex;
  }
  .boxMoaMiddle {
    display: flex;
    align-items: center;
    margin-top: 30px;
    margin-left: 20px;
    span {
      margin-right: 10px;
    }
    .moAinput {
      width: 85%;
    }
  }
  .boxMoaLeg {
    display: flex;
    margin-top: 30px;
    .boxMoaLegLeft {
      margin-left: 20px;
      margin-right: 10px;
    }
  }
  .boxMoaBottom {
    margin-top: 30px;
    margin-left: 20px;
  }
}
</style>
